/**
 * 
 */
package com.fyp.client.ptma.utils;

import java.io.File;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;

/**
 * @author yahya
 * 
 */
public final class Device
{
	public static final String APP_FOLDER = "ptma";

	public float getAvailableSDSpace()
	{
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());
		long bytesAvailable = (long) stat.getBlockSize()
				* (long) stat.getAvailableBlocks();
		return bytesAvailable / (1024.f * 1024.f);
	}

	public static void deletefile(String filePath)
	{
		try
		{
			File file = new File(filePath);
			if (file.exists())
			{
				file.delete();
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static boolean isSdPresentForReadWrite()
	{

		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state))
		{
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
		{
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else
		{
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}

		if (mExternalStorageAvailable == mExternalStorageWriteable == true)
			return true;
		else
			return false;

	}

	public static boolean createDirIfNotExists(String path)
	{
		boolean ret = true;

		File file = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath(), path);

		try
		{
			if (!file.exists())
			{
				if (!file.mkdirs())
				{

					ret = false;
				}
			}
		} catch (SecurityException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}

		return ret;
	}

	public static String getDeviceNumber(Context ctx)
	{
		TelephonyManager tManager = (TelephonyManager) ctx
				.getSystemService(Context.TELEPHONY_SERVICE);
		String uid = tManager.getDeviceId();
		return uid;
	}

	public static boolean isAppInstalled(Context ctx, String uri)
	{
		PackageManager pm = ctx.getPackageManager();
		boolean app_installed = false;
		try
		{
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			app_installed = true;
		} catch (PackageManager.NameNotFoundException e)
		{
			app_installed = false;
		}
		return app_installed;
	}
}
